package web.java.demo;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 当浏览器同服务器传参时，规定参数的统一编码方式
 * */
public class FilterEncoding implements Filter{

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		//可以将ServletRequst转化为HttpServletRequset
		final HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) res;
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		//代理get方式请求
		HttpServletRequest proxy=(HttpServletRequest)Proxy.newProxyInstance(
				request.getClass().getClassLoader(),	//指定当前代理对象的类加载器 
				new Class[]{HttpServletRequest.class}, 	//对目标对象实现的接口类型
				new InvocationHandler(){				//事件处理器
					
					@Override
					public Object invoke(Object proxy, Method method,
							Object[] args) throws Throwable {
						Object result=null;
						//获取执行事件的名称
						String methodName=method.getName();
						//对getParameter方法中的GET提交方式斤进行处理
						if("getParameter".equals(methodName)){
							//获取GET传参的请求数据
							String value=request.getParameter(args[0].toString());//传入的第一个参数，username
							//获取提交方式
							String methodSubmit=request.getMethod();
							if("GET".equalsIgnoreCase(methodSubmit)){
								//对字符串进行处理
								if(value!=null && !"".equals(value.trim())){
									value=new String(value.getBytes("ISO-8859-1"),"utf-8");
								}
							}
							return value;
						}else{
							//不是get请求的方法，按照原来的方式进行提交
							result=method.invoke(request,args);
						}
						//返回最终提交的参数
						return result;
					}
				}			
		);
		chain.doFilter(proxy,response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
